﻿using MediatR;
using Sgr.Application.Commands;
using Sgr.Application.Queries;
using Sgr.Identity.Services;
using Sgr.Security.VerifyCode;
using Sgr.UPMS.Domain.Users;

namespace Sgr.UPMS.Application.Commands.UserProfile
{
    public class BindPhoneCommandHandle : IRequestHandler<BindPhoneCommand, CommandResult<bool>>
    {
        private readonly IUserRepository _userRepository;
        private readonly ICurrentUser _currentUser;
        private readonly IVerifyCodeService _verifyCodeService;

        public BindPhoneCommandHandle(
            IUserRepository userRepository,
            ICurrentUser currentUser,
            IVerifyCodeService verifyCodeService)
        {
            _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
            _currentUser = currentUser ?? throw new ArgumentNullException(nameof(currentUser));
            _verifyCodeService = verifyCodeService ?? throw new ArgumentNullException(nameof(verifyCodeService));
        }

        public async Task<CommandResult<bool>> Handle(BindPhoneCommand request, CancellationToken cancellationToken)
        {
            // 1. 获取当前用户
            long userId = QueryHelper.GetUserId(_currentUser);
            User? user = await _userRepository.GetAsync(userId, cancellationToken);
            if (user == null)
                return CommandResult.NotFound<bool>("未找到指定的用户");

            // 2. 验证码校验
            bool isValidCode = await _verifyCodeService.VerifyAsync(
                ReceiverType.Phone,
                request.PhoneNumber,
                request.VerificationPurpose,
                request.VerificationCode,
                true,
                cancellationToken);

            if (!isValidCode)
                return CommandResult.Invalid<bool>(Constant.INVALID_VERIFYCODE_MESSAGE);

            // 3. 更新到仓储
            user.BindPhoneNumber(request.PhoneNumber, true);
            await _userRepository.UpdateAsync(user, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "绑定手机号码成功");
        }
    }
}